var page = require('webpage').create();
// var url =
// "https://treport.1hykj.com/enterpriseLoanReport?id=8a2831786cd6f5c0016cd6f5c08a0000";
//var url = "https://treport.1hykj.com/blackList?id=8a2132686d4214f7016d42379b26000c&expansion=true";
var url = "http://192.168.52.197:8080/blackList?id=8a2132686d4214f7016d42379b26000c&expansion=true";
// var url = "https://www.baidu.com/";
page.open(url, function(status) {
	console.log("Status: " + status);
	if (status === "success") {
		// page.render('example.png');
		console.log("page success");
		// page.render('example3.pdf');
		// var bodyHtml = page.evaluate(function(){
		// return document.querySelector('html').innerHTML;
		// });
		// console.log(bodyHtml);
	}
});

function waitFor(testFx) {
	setTimeout(
			function() {
				var condition = (typeof (testFx) === "string" ? eval(testFx)
						: testFx());
				phantom.exit();
			}, 5000);
};

function elementClick(el) {
	// var ev = document.createEvent("MouseEvent");
	// ev.initMouseEvent(
	// "click",
	// true /* bubble */, true /* cancelable */,
	// window, null,
	// 0, 0, 0, 0, /* coordinates */
	// false, false, false, false, /* modifier keys */
	// 0 /*left*/, null
	// );
	// el.dispatchEvent(ev);

	var ev = document.createEvent("HTMLEvents");
	ev.initMouseEvent("click", false, true);
	el.dispatchEvent(ev);
}

page.onLoadFinished = function() {
	console.log("page.onLoadFinished");
	// printArgs.apply(this, arguments);
	var p = page;
	p.viewportSize = {
		width : 1500,
		height : 5000
	};
	var f = function() {
		page.evaluate(function() {
//			var tds = document.querySelectorAll(".td-detail");
//			for (var i = 0; i < tds.length; i++) {
//				var ev = document.createEvent("HTMLEvents");
//				ev.initEvent("click", false, true);
//				tds[i].dispatchEvent(ev);
//				
//				
//				var clickEvent = document.createEvent("HTMLEvents");
//				clickEvent.initEvent("click",false,true);
//				 
//				tds[i].dispatchEvent(clickEvent);
//			}
			
			var clickEvent = document.createEvent("HTMLEvents");
			clickEvent.initEvent("click", false, true);
			document.querySelector(".td-detail").dispatchEvent(clickEvent);
			
			console.log(document.querySelector(".td-detail").innerHTML);
		});
		console.log("page out:", document.querySelectorAll(".td-detail"));
		// console.log("page out:", page.content);
		page.render('example5.pdf', {
			format : 'pdf',
			quality : '100'
		});
	};
	waitFor(f);
	// p.render('example4.pdf');
};

function printArgs() {
	var i, ilen;
	for (i = 0, ilen = arguments.length; i < ilen; ++i) {
		console.log("    arguments[" + i + "] = "
				+ JSON.stringify(arguments[i]));
	}
	console.log("");
}

page.onConsoleMessage = function() {
	console.log("page.onConsoleMessage");
	printArgs.apply(this, arguments);
};